import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:intl/intl.dart';
import 'package:shared_preferences/shared_preferences.dart';

void toastCenter(s) {
  EasyLoading.showToast(s);
}

void toastCButton(s) {
  EasyLoading.showToast(s, toastPosition: EasyLoadingToastPosition.bottom);
}

bool strCompare(String a, String b) {
  return a == b;
}

/// 判断字符串中是否包含 "http" 或 "https"
bool containsHttp(String input) {
  return input.contains("http") || input.contains("https");
}

DateTime? string2Date(
  String dateStr, {
  String pattern = "yyyy-MM-dd HH:mm:ss",
}) {
  final formatter = DateFormat(pattern);
  try {
    return formatter.parse(dateStr);
  } catch (e) {
    return null;
  }
}

String? date2String(DateTime date, {String pattern = "yyyy-MM-dd"}) {
  final formatter = DateFormat(pattern);
  try {
    return formatter.format(date);
  } catch (e) {
    print(e);
    return null;
  }
}

String? getHostPart(String ip) {
  // 使用 '.' 分割 IP 地址
  List<String> parts = ip.split('.');

  // 检查是否有足够的部分
  if (parts.length < 4) {
    return null; // 如果 IP 地址不合法，返回 null
  }

  // 返回第三个点后的部分（即第四部分）
  return parts[3]; // 注意：索引从0开始，第三个点后的部分是 parts[3]
}

// 配置 EasyLoading
void configLoading() {
  EasyLoading.instance
    ..displayDuration = const Duration(milliseconds: 2000)
    ..indicatorType = EasyLoadingIndicatorType.fadingCircle
    ..loadingStyle = EasyLoadingStyle.dark
    ..indicatorSize = 45.0
    ..radius = 10.0
    ..progressColor = Colors.yellow
    ..backgroundColor = Colors.green
    ..indicatorColor = Colors.yellow
    ..textColor = Colors.yellow
    ..maskColor = Colors.blue.withOpacity(0.5)
    ..userInteractions = true
    ..dismissOnTap = false
    ..customAnimation = MyCustomLoadingAnimation(); // 使用自定义动画
}

// 自定义 EasyLoading 动画类
class MyCustomLoadingAnimation extends EasyLoadingAnimation {
  @override
  Widget buildWidget(
    Widget child,
    AnimationController controller,
    AlignmentGeometry alignment, // 保持 AlignmentGeometry 类型
  ) {
    // 将 AlignmentGeometry 转换为 Alignment
    return ScaleTransition(
      scale: controller,
      alignment: alignment as Alignment, // 强制转换为 Alignment
      child: child,
    );
  }
}

String TOKEN_KEY = "TOKEN_KEY";
Future<void> saveToken(String token) async {
  var sp = await SharedPreferences.getInstance();
  await sp.setString(TOKEN_KEY, token);
}

Future<String> getToken() async {
  var sp = await SharedPreferences.getInstance();
  return sp.getString(TOKEN_KEY) ?? "";
}
